package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @Author by 孙有泽
 * @Date 2025/2/28 13:59
 * @Description 自定义切面类
 */
@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    /*
     * @author 孙有泽
     * @date 2025/2/28 14:04
     * @description 切入点表达式
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..))&& @annotation(com.sky.annotation.AutoFill)")
    public void repositoryPointcut() {}
    /*
     * @author 孙有泽
     * @date 2025/2/28 14:05
     * @description 前置通知
     */
    @Before("repositoryPointcut()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("执行了前置通知");
        //目标:对指定的增强方法获取参数对象 填充公共字段
        //通过joinPoint获取签名对象
        MethodSignature methodSignature=(MethodSignature) joinPoint.getSignature();
        //通过方法签名对象获取AutoFill注解对象
        AutoFill annotation = methodSignature.getMethod().getAnnotation(AutoFill.class);
        //获取注解@AutoFill的属性值
        OperationType value = annotation.value();
        //joinPoint.getArgs()获取方法参数
        Object[] args = joinPoint.getArgs();
        //判断参数数组是否有效,无效结束
        if (args == null || args.length == 0) {
            return;
        }
        //获取第一个参数
        Object arg = args[0];
        //准备当前时间和登录人的id
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //判断@AutoFill注解的属性值未 OptionType.Insert 填充4个字段
        if (value == OperationType.INSERT) {
            Method updateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            updateTime.invoke(arg,now);
            Method createTime = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            createTime.invoke(arg,now);
            Method updateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            updateUser.invoke(arg,currentId);
            Method createUser = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            createUser.invoke(arg,currentId);
        }else{
            Method updateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            updateTime.invoke(arg,now);
            Method updateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            updateUser.invoke(arg,currentId);
        }
    }
}
